/**
 * futures : masterlink.futures.filter.AuthFilter.java
 */
package masterlink.futures.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.springframework.http.HttpRequest;

import baytony.util.StringUtil;
import baytony.util.Util;
import baytony.util.log.Log;

import masterlink.futures.controller.LoginController;
import masterlink.futures.util.Constant;
import masterlink.futures.util.WebUtils;
import masterlink.futures.vo.Employee;

/**
 * TODO Write the description
 *
 * @author : tonyyang
 * Create date : 2011/10/28
 * @version 1.0.0	
 */
public class AuthFilter implements Filter {
	
	private static final Logger log=Log.getLogger(AuthFilter.class);
	private static final String DEFAULT="login";
	private FilterConfig config;
	private String login;

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest reqq=((HttpServletRequest)req);
		String url=reqq.getServletPath()+StringUtil.trim(reqq.getPathInfo());
		if(url.contains(login)){
			log.trace("{} going to login controller.",url);
			chain.doFilter(req, res);
		}else{
			Employee emp=WebUtils.getLogEmployee(reqq);
			if(emp==null){
				log.info("User from {} going to {} is not login, forward login",reqq.getRemoteAddr(),url);
				reqq.getRequestDispatcher("/login.jsp").forward(req, res);
			}else{
				log.info("Empno {} login, foward to {}", emp,url);
				chain.doFilter(req, res);
			}
		}
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		this.config=config;
		this.login=config.getInitParameter("LOGIN_URL");
		if(Util.isEmptyString(login)){
			this.login=DEFAULT;
		}
	}

}
